// Copyright  2012 Petr TALLA. [petr.talla@gmail.com]
// This file is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY;  without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
// [http://www.gnu.org/copyleft/lesser.html]
//=============================================================================

package tc.crase.db;

import java.util.Iterator;
import java.util.LinkedList;

public class Xdb implements Iterable<Xobject> {
	public int maxLinkId = 1;
	
	public String fileName = new String("");
	
	private LinkedList<Xobject> items = new LinkedList<Xobject>();
		
	private int maxid = 1;
	
	public Xdb() {
	}
	
	public String getName() {
		if (fileName.isEmpty()) return "UNKNOWN";
		String fn = fileName.substring(0, fileName.length()-6);
		if (fn.length() < 15) return fn;
		int form = fn.length() - 15;
		if (form < 0 ) form = 0;
		return "..." + fn.substring(form);
	}
	
	public Xobject createObject(int id) {
		Xobject xobject = new Xobject();
		initializeObject(xobject, id);
		return xobject;
	}
	
	public void removeObject(Xobject object) {
		items.remove(object);
	}
	
	public Xobject getById(int id) {
		Iterator<Xobject> ito = items.iterator();
				
		while ( ito.hasNext() ) {
			Xobject obj = ito.next();
			if (obj.id != id) continue;
			return obj;
		}
		
		return null;
	}
	
	@Override
	public Iterator<Xobject> iterator() {
		return items.iterator();
	}
	
	/*XattrLNK getLnk(AttrId id) {
		Iterator<Xobject> it = items.iterator();
		while(it.hasNext()) {
			Xobject object = it.next();
			
			for( Xattr attr : object) {
				XattrLNK lnk = attr.getAsLNK();
				if (lnk == null) continue;
				if ( id.getId() == lnk.getId() ) {
					return lnk;
				}
			}
		}
		
		assert false;
		
		return null;
	}*/
	
	protected void onRemove(Xobject xobj) {
		items.remove(xobj);
	}
	
	protected void initializeObject(Xobject xobject, int id) {
		if (id < 0)
		{	xobject.id = maxid++;
		}
		else
		{	xobject.id = id;
			if (maxid <= id) maxid = id+1;			
		}
		
		items.add(xobject);
		
		xobject.db = this;
	}
}
